<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
    <style>
        /* =========  通用响应式  ========= */
        body {
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
        }

        .nav {
            height: 48px;
            line-height: 48px;
            text-align: center;
            background: #f5f5f5;
            font-size: 18px;
        }

        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
        }

        #chess_area {
            width: 100%;
            max-width: 600px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        #chess {
            max-width: 100%;
            height: auto;
            border: 1px solid #ccc;
        }

        #screen {
            width: 100%;
            max-width: 600px;
            height: clamp(40px, 12vw, 50px);
            line-height: clamp(40px, 12vw, 50px);
            margin-top: 10px;
            background: #fff;
            font-size: clamp(16px, 4vw, 22px);
            text-align: center;
        }

        #chat_area {
            width: 100%;
            max-width: 600px;
            margin-top: 20px;
            height: clamp(300px, 50vh, 400px);
            border: 2px solid #fff;
            border-radius: 5px;
            background: #fff;
            display: flex;
            flex-direction: column;
        }

        #chat_show {
            flex: 1;
            overflow-y: auto;
            background: #fec;
            padding: 6px;
        }

        #msg_show {
            display: flex;
            align-items: center;
            padding: 6px;
        }

        #chat_input {
            flex: 1;
            height: 48px;
            font-size: 16px;
            padding: 0 8px;
            border: 2px solid #fec;
            border-radius: 5px;
            box-sizing: border-box;
        }

        #chat_button {
            width: 100px;
            height: 48px;
            margin-left: 8px;
            background: #fec;
            font-size: 16px;
            border: 2px solid #fec;
            border-radius: 5px;
            cursor: pointer;
        }

        #chat_button:active {
            background: rgb(149, 127, 83);
        }

        .self_msg,
        .peer_msg {
            max-width: 80%;
            padding: 8px 14px;
            margin: 4px 0;
            font-size: clamp(13px, 2vw, 16px);
            line-height: 1.3;
            border-radius: 5px;
            word-break: break-all;
        }

        .self_msg {
            margin-left: auto;
            background: rgb(7, 190, 102);
            color: #fff;
        }

        .peer_msg {
            margin-right: auto;
            background: rgb(93, 218, 243);
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <canvas id="chess"></canvas>
            <div id="screen">等待玩家连接中...</div>
        </div>

        <div id="chat_area">
            <div id="chat_show"></div>
            <div id="msg_show">
                <input type="text" id="chat_input" placeholder="说点什么...">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>

    <script>
        (function () {
            const BOARD_ROW_AND_COL = 15;
            let chessBoard = [];
            let room_info = null;
            let is_me = false;
            const canvas = document.getElementById('chess');
            const ctx = canvas.getContext('2d');
            const chatShow = document.getElementById('chat_show');

            /* -------- 棋盘尺寸自适应 -------- */
            let CELL_PX;
            function resizeBoard() {
                const maxPx = window.innerWidth < 768 ? window.innerWidth * 0.9 : 600;
                canvas.width = canvas.height = maxPx;
                CELL_PX = maxPx / BOARD_ROW_AND_COL;
                drawBoard();
            }
            window.addEventListener('resize', resizeBoard);

            /* -------- WebSocket -------- */
            const ws_url = "ws://" + location.host + "/room";
            const ws_hdl = new WebSocket(ws_url);
            window.onbeforeunload = () => ws_hdl.close();
            ws_hdl.onopen = () => console.log("房间连接已打开");
            ws_hdl.onclose = () => alert("房间长连接断开");
            ws_hdl.onerror = () => alert("房间长连接出错");

            /* -------- 棋盘 & 落子 -------- */
            function initBoard() {
                for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                    chessBoard[i] = [];
                    for (let j = 0; j < BOARD_ROW_AND_COL; j++) chessBoard[i][j] = 0;
                }
            }
            function drawBoard() {
                ctx.strokeStyle = "#BFBFBF";
                for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                    ctx.beginPath();
                    ctx.moveTo(CELL_PX * 0.5 + i * CELL_PX, CELL_PX * 0.5);
                    ctx.lineTo(CELL_PX * 0.5 + i * CELL_PX, canvas.height - CELL_PX * 0.5);
                    ctx.stroke();
                    ctx.beginPath();
                    ctx.moveTo(CELL_PX * 0.5, CELL_PX * 0.5 + i * CELL_PX);
                    ctx.lineTo(canvas.width - CELL_PX * 0.5, CELL_PX * 0.5 + i * CELL_PX);
                    ctx.stroke();
                }
            }
            function drawPiece(col, row, isWhite) {
                if (col < 0 || row < 0) return;
                const x = CELL_PX * 0.5 + col * CELL_PX;
                const y = CELL_PX * 0.5 + row * CELL_PX;
                const r = CELL_PX * 0.4;
                const grad = ctx.createRadialGradient(x + 2, y - 2, r, x + 2, y - 2, 0);
                grad.addColorStop(0, isWhite ? "#D1D1D1" : "#0A0A0A");
                grad.addColorStop(1, isWhite ? "#F9F9F9" : "#636766");
                ctx.fillStyle = grad;
                ctx.beginPath();
                ctx.arc(x, y, r, 0, 2 * Math.PI);
                ctx.fill();
            }

            /* -------- 点击 / 触摸 -------- */
            function handleClick(x, y) {
                if (!is_me) return alert("等待对方走棋...");
                const rect = canvas.getBoundingClientRect();
                const logicX = x * (canvas.width / rect.width);
                const logicY = y * (canvas.height / rect.height);
                const col = Math.floor(logicX / CELL_PX);
                const row = Math.floor(logicY / CELL_PX);
                if (col < 0 || col > 14 || row < 0 || row > 14) return;
                if (chessBoard[row][col] !== 0) return alert("当前位置已有棋子！");
                sendChess(row, col);
            }
            canvas.addEventListener('click', e => {
                const rect = canvas.getBoundingClientRect();
                handleClick(e.clientX - rect.left, e.clientY - rect.top);
            });
            canvas.addEventListener('touchstart', e => {
                e.preventDefault();
                const rect = canvas.getBoundingClientRect();
                const touch = e.touches[0];
                handleClick(touch.clientX - rect.left, touch.clientY - rect.top);
            });

            function sendChess(row, col) {
                const msg = {
                    optype: "put_chess",
                    room_id: room_info.room_id,
                    uid: room_info.uid,
                    row: row,
                    col: col
                };
                ws_hdl.send(JSON.stringify(msg));
            }

            /* -------- 聊天 -------- */
            document.getElementById('chat_button').onclick = () => {
                const input = document.getElementById('chat_input');
                const txt = input.value.trim();
                if (!txt) return;
                ws_hdl.send(JSON.stringify({
                    optype: "chat",
                    room_id: room_info.room_id,
                    uid: room_info.uid,
                    message: txt
                }));
                input.value = '';
            };

            /* -------- 消息入口 -------- */
            ws_hdl.onmessage = function (evt) {
                const info = JSON.parse(evt.data);
                if (info.optype === 'room_ready') {
                    room_info = info;
                    is_me = room_info.uid === room_info.white_id;
                    initBoard();
                    drawBoard();
                    document.getElementById('screen').innerText = is_me ? '轮到己方走棋...' : '轮到对方走棋...';
                }
                else if (info.optype === 'put_chess') {
                    if (!info.result) { alert(info.reason); return; }
                    const isWhite = info.uid === room_info.white_id;   // ← 关键：按后端广播 UID 决定颜色
                    drawPiece(info.col, info.row, isWhite);
                    chessBoard[info.row][info.col] = 1;
                    is_me = info.uid !== room_info.uid;
                    document.getElementById('screen').innerText = is_me ? '轮到己方走棋...' : '轮到对方走棋...';
                    if (info.winner != 0) {
                        document.getElementById('screen').innerText =
                            info.winner == room_info.uid ? info.reason : '抱歉，你输了';
                        const btn = document.createElement('button');
                        btn.textContent = '返回游戏大厅';
                        btn.onclick = () => { ws_hdl.close(); location.replace('/game_hall.html'); };
                        document.getElementById('chess_area').appendChild(btn);
                    }
                }
                else if (info.optype === 'chat') {
                    if (!info.result) { alert(info.reason); return; }
                    const p = document.createElement('p');
                    p.className = info.uid == room_info.uid ? 'self_msg' : 'peer_msg';
                    p.innerText = info.message;
                    chatShow.appendChild(p);

                    // ① 只滚容器
                    chatShow.scrollTop = chatShow.scrollHeight;

                    // ② 不滚整个页面
                    
                }
            };

            /* 首次渲染 */
            resizeBoard();
        })();
    </script>
</body>

</html>